/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.app;

import com.hboxs.asl.Constant;
import com.hboxs.asl.FileInfo;
import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.ProductImage;
import com.hboxs.asl.service.AreaService;
import com.hboxs.asl.service.FileService;
import com.hboxs.asl.service.MemberService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller - 共用
 */
@Controller("appCommonController")
@RequestMapping("/app/com")
public class CommonController {

    protected Logger logger = Logger.getLogger(getClass().getName());

    @Resource(name = "areaServiceImpl")
    private AreaService areaService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "fileServiceImpl")
    private FileService fileService;

    /**
     * 地区Tree
     */
    @RequestMapping(value = "/areaTree", method = RequestMethod.GET)
    public
    @ResponseBody
    Object list() {
        return JsonMessage.success(areaService.findRoots());
    }

    /**
     * 上传语音
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadMedia", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage uploadMedia(MultipartFile file) {
        String url = null;
        try {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
            if(!Constant.MEDIA_TYPE.equalsIgnoreCase(suffix)) {
                return JsonMessage.error("上传音频文件格式只能是amr");
            }
            // 1. 需要FileType
            FileInfo.FileType fileType = FileInfo.FileType.media;
            // 2. 需要ImageType
            ProductImage.imageType type = ProductImage.imageType.defaultImage;
            // 3. 调用fileService upload 方法
            url = fileService.upload(fileType, file, false, type.toString());
            // 4. 返回语音URL
            if (url == null) {
                return JsonMessage.error("上传失败！");
            } else {
                return JsonMessage.success(url);
            }
        } catch (Exception e) {
            if(e instanceof ProtocolException){
                return JsonMessage.success(url);
            }
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 上传语音
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadMediaTest", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage uploadMediaTest(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
            if(!Constant.MEDIA_TYPE.equalsIgnoreCase(suffix)) {
                return JsonMessage.error("上传音频文件格式只能是amr");
            }
            FileInfo.FileType fileType = FileInfo.FileType.media;
            String url = fileService.uploadMedia(fileType, file);
            if (url == null) {
                return JsonMessage.error("上传失败！");
            } else {
                return JsonMessage.success(url);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 上传图片
     *
     * @param imageType 图片类型
     * @param file      图片文件
     * @return 图片链接
     */
    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage uploadImage(String imageType, MultipartFile file) {
        try {

            // 1. 需要FileType
            FileInfo.FileType fileType = FileInfo.FileType.image;
            if (!fileService.isValid(fileType, file)) {
                return JsonMessage.error("上传图片大小或格式不正确");
            }
            // 2. 需要ImageType
            ProductImage.imageType type = ProductImage.imageType.defaultImage;
            if (StringUtils.isNotEmpty(imageType)) {
                try {
                    type = ProductImage.imageType.valueOf(imageType);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 3. 调用fileService upload 方法
            String url = fileService.upload(fileType, file, false, type.toString());
            // 4. 返回图片URL
            if (url == null) {
                return JsonMessage.error("图片上传失败！");
            } else {
                return JsonMessage.success(url);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 上传多图片
     *
     * @param imageType 图片类型
     * @param files      图片文件
     * @return 图片链接
     */
    @RequestMapping(value = "/uploadImages", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage uploadImages(String imageType, MultipartFile[] files) {
        List<String> urlList = new ArrayList<String>();
        for(MultipartFile file : files) {
            try {
                // 1. 需要FileType
                FileInfo.FileType fileType = FileInfo.FileType.image;
                if (!fileService.isValid(fileType, file)) {
                    return JsonMessage.error("上传图片大小或格式不正确");
                }
                // 2. 需要ImageType
                ProductImage.imageType type = ProductImage.imageType.defaultImage;
                if (StringUtils.isNotEmpty(imageType)) {
                    try {
                        type = ProductImage.imageType.valueOf(imageType);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                // 3. 调用fileService upload 方法
                String url = fileService.upload(fileType, file, false, type.toString());
                urlList.add(url);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        if(urlList.size() > 0) {
            return JsonMessage.success(urlList);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 判断登录的token是否过期
     *
     * @return json
     */
    @RequestMapping(value = "/time", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage time() {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if (member.getTokenExpire() != null && member.getTokenExpire().before(new Date())) {
                return JsonMessage.error("时间过期");
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 错误提示
     */
    @RequestMapping("/error")
    public String error() {
        return "/yijing/common/error";
    }

    /**
     * 资源不存在
     */
    @RequestMapping("/404")
    public String resourceNotFound() {
        return "/yijing/common/404";
    }

}